<?php

namespace App\Http\Middleware;

use App\Models\admin\AdminPermissionModel;
use App\Models\admin\AdminRoleModel;
use App\Models\admin\AdminUserModel;
use Closure;
use Illuminate\Http\Request;
use lxs\api\ApiResponse;
use Symfony\Component\HttpFoundation\Response;

class CheckPermis
{
    /**
     * Handle an incoming request.
     *
     * @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $uid = $request->system_uid;
        $code = $request->path();
        $systemUser = AdminUserModel::where('id', $uid)->first();
        $permission = AdminPermissionModel::where('code', $code)->first();
        if (!$permission) {
            return $next($request);
        }
        $roleId = $systemUser->role_id;
        $role = AdminRoleModel::where('id', $roleId)->first();
        if (!$role) {
            return ApiResponse::apiResponseData(100, '没有权限');
        }
        if ($role->is_super == 1) {
            return $next($request);
        }
        $rolePermission = $role->permission;
        if (!in_array($permission->id, explode(',', $rolePermission))) {
            return ApiResponse::apiResponseData(100, '没有权限');
        }
        return $next($request);
    }
}
